package glin

import (
	"encoding/json"
	"fmt"
	"time"
)

// 图形验证码
type CaptchaUser struct {
	Val  string    //变量
	Time time.Time //当前时间
}

// 图形校验
type StoreCaptcha struct {
	Name    string  //本次要使用的key
	Context Context //
}

// 设置数据
func (store *StoreCaptcha) Set(id string, value string) (err error) {
	session, err := StoreSessions.Get(store.Context.Request(), GDefaultConfig.Session.SessionId)
	if err != nil {
		return err
	}
	user := make(map[string]CaptchaUser)
	user[store.Name] = CaptchaUser{
		Val:  value,
		Time: time.Now(),
	}
	data, _ := json.Marshal(user)
	session.Values["captcha"] = data
	return session.Save(store.Context.Request(), store.Context.Response())

}

// Get returns stored digits for the captcha id. Clear indicates
// whether the captcha must be deleted from the store.
func (store *StoreCaptcha) Get(id string, clear bool) string {

	session, err := StoreSessions.Get(store.Context.Request(), GDefaultConfig.Session.SessionId)
	if err != nil {
		return ""
	}
	val, ok := session.Values["captcha"]
	if !ok {
		return ""
	}
	user := make(map[string]CaptchaUser)
	data := val.([]byte)
	err = json.Unmarshal(data, &user)
	if err != nil {
		return ""
	}
	cap, ok := user[store.Name]
	if !ok {
		return ""
	}
	if cap.Time.Unix()+int64(30) <= time.Now().Unix() {
		return ""
	}
	delete(user, store.Name)       //需要删除数据
	sdata, _ := json.Marshal(user) //需要再保存数据
	session.Values["captcha"] = sdata
	session.Save(store.Context.Request(), store.Context.Response())
	return cap.Val
}

// Verify captcha's answer directly
func (store *StoreCaptcha) Verify(id, answer string, clear bool) bool {
	fmt.Println("StoreCaptcha Verify id=", id, "answer=", answer, "clear=", clear)
	val := store.Get(id, clear)
	if val == "" {
		return false
	}
	if answer == "" {
		return false
	}
	if val != answer {
		return false
	}
	return true
}
